import com.im30.jenkins.pipeline.utils.BuildConfig

def call() {
    properties([
            gitLabConnection('GitLab'),
            buildDiscarder(logRotator(artifactDaysToim30Str: '', artifactNumToim30Str: '', daysToim30Str: '7', numToim30Str: '50'))
    ])

    dockerNode.javaBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        String comment = ""
        try {
            stage('Preparation') {
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: "origin/${env.gitlabSourceBranch}"]],
                    extensions: [[
                         $class: 'PreBuildMerge',
                         options: [
                             fastForwardMode: 'FF',
                             mergeRemote: 'origin',
                             mergeStrategy: 'DEFAULT',
                             mergeTarget: "${env.gitlabTargetBranch}"
                         ],
                     ]],
                    userRemoteConfigs: scm.userRemoteConfigs
                ])
            }

            buildConfig = BuildConfig.load(this)
            stage('Test') {
                timeout(40) {
                    int status = sh(
                            encoding: 'UTF-8',
                            returnStatus: true,
                            script: 'mvn -q -U -Dmaven.test.failure.ignore clean compile test >err.log 2>&1'
                    )
                    if (status != 0) {
                        String errorLog = readFile(file: "err.log")
                        int idx = errorLog.indexOf('[ERROR] COMPILATION ERROR')
                        // 如果找不到编译错误，就展示普通错误
                        if (idx <= 0) {
                            idx = errorLog.indexOf('[ERROR]')
                        }
                        errorLog = errorLog.substring(idx)
                        throw new Exception(errorLog)
                    }
                }
            }
            stage('Report') {
                timeout (120) {
                    // sh 'mvn sonar:sonar -Dsonar.analysis.mode=preview -Dsonar.host.url=http://sonar-tx.http.svc.pre.ali.im30 -Dsonar.login=27023b0400857c5d5ae67f312fcd154006a020ce' | awk \'match($0, /Phab-Lint: .*/) {print substr($0, RSTART+11, RLENGTH-1)}\' | tee -a .phabricator-lint'
                    // 后续有精力再优化到直接显示到代码上。

                    try {
                        sh 'mvn jacoco:report'
                        mavenUtil.report()
                        // TODO unit test 失败应该让 job 变成 unstable
                    } catch (err) {
                        // ignore No test report files were found error
                        echo err.getMessage()
                    }

                    if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
                        comment = "编译通过，少年干得不错！"
                        isSuccess = true
                    } else {
                        comment = "少年，这个提交似乎有点问题！"
                        isSuccess = false
                    }
                }

                // 当前认为 jenkins 的 unstable 状态对应 gitlab 的 success
                // 但 jenkins 不会 approve 这个 merge request
                updateGitlabCommitStatus(name: 'build', state: 'success')
                try {
                    if (isSuccess) {
                        approveGitLabMR()
                    } else {
                        unapproveGitLabMR()
                    }
                } catch (err) {
                    echo 'approve or unapprove failed'
                    echo err.message
                }

            }
            stage('snapshot-check') {
                try {
                    String output = mavenUtil.snapshotCheck(env.gitlabTargetBranch)
                    if (output != '') {
                        comment += "\n\n合并到 master 的代码不能有 SNAPSHOT！\n```\n${output}\n```\n"
                    }
                } catch(err) {
                    echo err.getMessage()
                    String url = "https://open.feishu.cn/open-apis/bot/v2/hook/112510b3-9588-4935-826d-43508eb60442"
                    notifyUtil.notifyText(url, "SNAPSHOT 检测失败", "${env.BUILD_URL}\\n${e.message}")
                }
            }
        } catch (err) {
            currentBuild.result = 'FAILURE'
            String errMsg = err.getMessage()
            if (errMsg != null && errMsg.length() > 10000) {
                errMsg = errMsg.substring(0, 9000) + "\n ......\n"
            }
            errMsg = "```\n${errMsg}```\n"
            comment += "该提交无法通过通过 CI 流程！！\n\n" + errMsg
            isSuccess = false
            updateGitlabCommitStatus(name: 'build', state: 'failed')
            try {
                unapproveGitLabMR()
            } catch (e) {
                echo 'unapprove failed'
                echo e.message
            }

        } finally {
            addGitLabMRComment(comment: comment)

            deleteDir()
        }
    }
}